import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../providers/products_provider.dart';
import '../widgets/product_card.dart';
import '../models/product.dart';

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  final ScrollController _scrollController = ScrollController();
  final TextEditingController _searchCtrl = TextEditingController();

  @override
  void initState() {
    super.initState();
    final p = context.read<ProductsProvider>();
    p.loadCategories();
    p.refresh();
    _scrollController.addListener(_onScroll);
  }

  void _onScroll() {
    final p = context.read<ProductsProvider>();
    if (_scrollController.position.pixels > _scrollController.position.maxScrollExtent - 200) {
      p.loadMore();
    }
  }

  @override
  void dispose() {
    _scrollController.dispose();
    _searchCtrl.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Consumer<ProductsProvider>(builder: (context, p, _) {
      return Scaffold(
        appBar: AppBar(
          title: const Text('商品列表'),
          bottom: PreferredSize(
            preferredSize: const Size.fromHeight(56),
            child: Padding(
              padding: const EdgeInsets.all(8.0),
              child: TextField(
                controller: _searchCtrl,
                decoration: InputDecoration(
                  hintText: '搜索关键字...',
                  prefixIcon: const Icon(Icons.search),
                  suffixIcon: _searchCtrl.text.isNotEmpty
                      ? IconButton(
                          icon: const Icon(Icons.clear),
                          onPressed: () {
                            _searchCtrl.clear();
                            p.setQuery(null);
                            p.refresh();
                          },
                        )
                      : null,
                  border: const OutlineInputBorder(),
                ),
                onSubmitted: (v) {
                  p.setQuery(v);
                  p.refresh();
                },
              ),
            ),
          ),
        ),
        body: RefreshIndicator(
          onRefresh: () async => p.refresh(),
          child: CustomScrollView(
            controller: _scrollController,
            slivers: [
              SliverToBoxAdapter(
                child: _buildCategories(p),
              ),
              if (p.isRefreshing && p.items.isEmpty)
                const SliverFillRemaining(child: Center(child: CircularProgressIndicator()))
              else if (p.errorMessage != null && p.items.isEmpty)
                SliverFillRemaining(
                  child: Center(
                    child: Column(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        const Icon(Icons.error_outline, size: 48),
                        const SizedBox(height: 12),
                        Text(p.errorMessage ?? '加载失败'),
                        const SizedBox(height: 12),
                        ElevatedButton(onPressed: () => p.refresh(), child: const Text('重试')),
                      ],
                    ),
                  ),
                )
              else
                SliverList.builder(
                  itemCount: p.items.length + 1,
                  itemBuilder: (ctx, i) {
                    if (i < p.items.length) {
                      final product = p.items[i];
                      return ProductCard(
                        product: product,
                        onTap: () => Navigator.pushNamed(context, '/detail', arguments: product),
                      );
                    }
                    // 底部区域：加载或“没有更多数据”
                    if (p.isLoading) {
                      return const Padding(
                        padding: EdgeInsets.symmetric(vertical: 24),
                        child: Center(child: CircularProgressIndicator()),
                      );
                    }
                    if (!p.hasMore) {
                      return const Padding(
                        padding: EdgeInsets.symmetric(vertical: 24),
                        child: Center(child: Text('没有更多数据')),
                      );
                    }
                    return const SizedBox.shrink();
                  },
                ),
            ],
          ),
        ),
      );
    });
  }

  Widget _buildCategories(ProductsProvider p) {
    if (p.categoriesLoading) {
      return const Padding(
        padding: EdgeInsets.all(12),
        child: SizedBox(height: 32, child: Center(child: CircularProgressIndicator(strokeWidth: 2))),
      );
    }
    if (p.categoriesError != null) {
      return Padding(
        padding: const EdgeInsets.all(12),
        child: Row(
          children: [
            const Icon(Icons.error_outline),
            const SizedBox(width: 8),
            Expanded(child: Text('分类加载失败')),
            TextButton(onPressed: p.loadCategories, child: const Text('重试')),
          ],
        ),
      );
    }
    return SingleChildScrollView(
      scrollDirection: Axis.horizontal,
      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 8),
      child: Row(
        children: [
          ChoiceChip(
            label: const Text('全部'),
            selected: p.category == null,
            onSelected: (s) {
              p.setCategory(null);
              p.refresh();
            },
          ),
          const SizedBox(width: 8),
          ...p.categories.map((c) => Padding(
                padding: const EdgeInsets.only(right: 8),
                child: ChoiceChip(
                  label: Text(c),
                  selected: p.category == c,
                  onSelected: (s) {
                    p.setCategory(s ? c : null);
                    p.refresh();
                  },
                ),
              )),
          const SizedBox(width: 8),
          OutlinedButton.icon(
            onPressed: () {
              p.clearFilters();
              _searchCtrl.clear();
              p.refresh();
            },
            icon: const Icon(Icons.filter_alt_off),
            label: const Text('清空条件'),
          ),
        ],
      ),
    );
  }
}